<?php

namespace app\api\controller;

use think\Db;

class Wxnotify
{
    // 微信支付回调
    public function notify()
    {
        $wx_service = new \wx\WeixinService();
        // php7 不支持// $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $xml = file_get_contents('php://input');
        //将服务器返回的XML数据转化为数组
        $wx_data = $wx_service->xmlToArray($xml);
        // 保存微信服务器返回的签名sign
        $data_sign = $wx_data['sign'];
        // sign不参与签名算法
        unset($wx_data['sign']);
        $sign = $wx_service->getPaySign($wx_data);

        // 判断签名是否正确  判断支付状态
        if (($sign === $data_sign) && ('SUCCESS' == $wx_data['return_code']) && ('SUCCESS' == $wx_data['result_code'])) {
            $result = $wx_data;
            //获取服务器返回的数据
            $order_sn = $wx_data['out_trade_no'];			//订单单号
            $openid = $wx_data['openid'];					//付款人openID
            $total_fee = round($wx_data['total_fee'] / 100, 2);			//付款金额
            $transaction_id = $wx_data['transaction_id']; 	//微信支付流水号

            // 先去掉缓存
            // $get_cache = cache('wxnotify_'.$order_sn);
            // if (!$get_cache) {
            //     cache('wxnotify_'.$order_sn, 1, 120);
            $order_info = Db::name('order')->find($order_sn);
            if ($order_info && 0 == $order_info['status']) {
                $product_name = '';
                $time = time();
                $red_packet = [];
                $total_red_packet = $gang_supply_cost = $supply_cost = $total_real_supply = 0;
                $gang_master_packet_total = $gang_packet_total = $fans_packet_total = 0;
                $gang_info = Db::name('gang')->find($order_info['gang_id']);
                $gang_type = Db::name('gang_type')->find($gang_info['type_id']);
                foreach ($order_info['product'] as $key => $value) {
                    $supply_price = $real_supply = 0;
                    $product_info = Db::name('product')->find($value['product_id']);
                    $product_name .= $product_info['name'].' ';
                    $number = intval($value['number']);
                    foreach ($product_info['specifications'] as $item) {
                        if ($item['title'] == $value['specifications']) {
                            $supply_price = round($item['supply_price'], 2);
                            $real_supply = round($item['real_supply'], 2);
                            break;
                        }
                    }
                    if ($supply_price > 0) {
                        // 供货价 = 官方供货价 + 帮会加价
                        $raise_price = round($gang_type['raise_price_list'][$product_info['brand']][$product_info['type']] / 100 + 1, 4);
                        $gang_supply_price = round($raise_price * $supply_price, 2);
                        $gang_price = Db::name('gang_product')->where(['gang_id' => $order_info['gang_id'], 'product_id' => $value['product_id'], 'specifications' => $value['specifications']])->find();
                        // 先发红包 只是是未结算的 不能拆开
                        // 帮主包 = 帮会价-供应价-粉丝包
                        $gang_master_money = round($gang_price['gang_price'] - $gang_supply_price - $gang_price['fans_reward'], 2) * $number;
                        $gang_master_packet_total += $gang_master_money;
                        if ($gang_master_money > 0) {
                            $total_red_packet += $gang_master_money;
                            $arr_index = array_search('帮主包', array_column($red_packet, 'type'));
                            if (false === $arr_index) {
                                $red_packet[] = ['type' => '帮主包', 'money' => round($gang_master_packet_total, 2), 'user_id' => $gang_info['user_id']];
                            } else {
                                $red_packet[$arr_index] = ['type' => '帮主包', 'money' => round($gang_master_packet_total, 2), 'user_id' => $gang_info['user_id']];
                            }
                        }
                        // 帮会包 = 零售价-帮会价(需要判断是不是本帮会成员购买，如果是以帮会价购买 就没有此包)
                        if (!$order_info['buyer_ismember']) {
                            $gang_packet_price = round($gang_price['retail_price'] - $gang_price['gang_price'], 2) * $number;
                            $gang_packet_total += $gang_packet_price;
                            if ($gang_packet_price > 0) {
                                $total_red_packet += $gang_packet_price;
                                $arr_index = array_search('帮会包', array_column($red_packet, 'type'));
                                if (false === $arr_index) {
                                    $red_packet[] = ['type' => '帮会包', 'money' => round($gang_packet_total, 2), 'user_id' => $order_info['seller']];
                                } else {
                                    $red_packet[$arr_index] = ['type' => '帮会包', 'money' => round($gang_packet_total, 2), 'user_id' => $order_info['seller']];
                                }
                            }
                        }
                        // 粉丝包
                        if ($order_info['inviter_id'] && $gang_price['fans_reward'] > 0) {
                            $fans_packet_price = round($gang_price['fans_reward'], 2) * $number;
                            $fans_packet_total += $fans_packet_price;
                            if ($fans_packet_price > 0) {
                                $total_red_packet += $fans_packet_price;
                                $arr_index = array_search('粉丝包', array_column($red_packet, 'type'));
                                if (false === $arr_index) {
                                    $red_packet[] = ['type' => '粉丝包', 'money' => round($fans_packet_total, 2), 'user_id' => $order_info['inviter_id']];
                                } else {
                                    $red_packet[$arr_index] = ['type' => '粉丝包', 'money' => round($fans_packet_total, 2), 'user_id' => $order_info['inviter_id']];
                                }
                            }
                        }
                    }
                    // 合计
                    // 供货价成本
                    $supply_cost += $supply_price * $number;
                    // 记录目前的供货价
                    $order_info['product'][$key]['real_supply'] = $real_supply;
                    $order_info['product'][$key]['gang_supply_price'] = $gang_supply_price;
                    // 帮主价成本
                    $gang_supply_cost += $gang_supply_price * $number;
                    $total_real_supply += $real_supply * $number;
                }
                $update_row = ['pay_time' => $time, 'status' => 1, 'openid' => $openid, 'total_fee' => $total_fee, 'transaction_id' => $transaction_id, 'product' => $order_info['product']];
                $update_row['supply_cost'] = $supply_cost;
                $update_row['gang_supply_cost'] = $gang_supply_cost;
                $update_row['total_red_packet'] = $total_red_packet;
                $update_row['total_real_supply'] = $total_real_supply;
                if ($red_packet) {
                    $update_row['red_packet'] = $red_packet;
                    // 增加待结算金额
                    notSettlemetnChange($update_row);
                }
                //更新数据库
                Db::name('order')->where(['id' => $order_sn])->update($update_row);
                // 发红包
                if ($update_row['red_packet']) {
                    $red_packet_list = [];
                    foreach ($update_row['red_packet'] as $kk => $vv) {
                        $red_packet_list[] = ['user_id' => $vv['user_id'], 'ct' => $time, 'from_user_id' => $order_info['buyer'], 'order_id' => $order_info['id'], 'not_open' => 1, 'not_settlemetn' => 1, 'money' => round($vv['money'], 2), 'type' => $vv['type']];
                    }
                    if ($red_packet_list) {
                        Db::name('red_packet')->insertAll($red_packet_list);
                    }
                }
                // 发送模板消息 付款成功
                $wxgzh_service = new \wx\WxgzhService();
                $user_info = Db::name('user')->where('openid', $openid)->find();
                $admin_info = Db::name('admin')->find($order_info['admin_id']);
                $address_info = Db::name('address')->where('id', $order_info['address'][0]['address_id'])->find();
                if ($admin_info['gzh_openid']) {
                    // 发送公众号模板消息（给供应商）
                    $data = [
                            'first' => ['value' => '买家下单啦！'],
                            'keyword1' => ['value' => strval($user_info['name'])],
                            'keyword2' => ['value' => strval(date('Y-m-d H:i:s', time()))],
                            'keyword3' => ['value' => strval($product_name)],
                            'keyword4' => ['value' => strval($update_row['total_real_supply'].'元')],
                            'keyword5' => ['value' => strval($address_info['phone'])],
                            'remark' => ['value' => '买家已付款，请及时发货', 'color' => '#173177'],
                        ];
                    $wxgzh_service->sendTemplateMsg($admin_info['gzh_openid'], 'D9_B5cFMv05Pbr8mFa04_4_EIAvUuYY2ZnnihRQ_-h0', $data);
                }
                if ($gang_info) {
                    $gang_master_info = Db::name('user')->find($gang_info['user_id']);
                    if ($gang_master_info['gzh_openid']) {
                        // 发送公众号模板消息（给帮主）
                        $data = [
                                'first' => ['value' => '你的帮会成员下单啦，恭喜！'],
                                'keyword1' => ['value' => strval($user_info['name'])],
                                'keyword2' => ['value' => strval(date('Y-m-d H:i:s', time()))],
                                'keyword3' => ['value' => strval($product_name)],
                                'keyword4' => ['value' => strval($order_info['total_money'].'元')],
                                'keyword5' => ['value' => strval($address_info['phone'])],
                                'remark' => ['value' => '您的会员确认收货后，你将得到'.round($gang_master_packet_total, 2).'元的现金红包 ，请多多做好会员的服务工作。', 'color' => '#173177'],
                            ];
                        $wxgzh_service->sendTemplateMsg($gang_master_info['gzh_openid'], 'D9_B5cFMv05Pbr8mFa04_4_EIAvUuYY2ZnnihRQ_-h0', $data,'pages/index/welcome');
                    }
                }
                $arr_index = array_search('帮会包', array_column($red_packet, 'type'));
                if (false !== $arr_index) {
                    $gang_member_info = Db::name('user')->find($order_info['seller']);
                    if ($gang_member_info['gzh_openid']) {
                        // 发送公众号模板消息（给帮会成员）
                        $data = [
                                'first' => ['value' => '你的朋友下单啦，恭喜！'],
                                'keyword1' => ['value' => strval($user_info['name'])],
                                'keyword2' => ['value' => strval(date('Y-m-d H:i:s', time()))],
                                'keyword3' => ['value' => strval($product_name)],
                                'keyword4' => ['value' => strval($order_info['total_money'].'元')],
                                'keyword5' => ['value' => strval($address_info['phone'])],
                                'remark' => ['value' => '你的朋友确认收货后，你将得到'.round($gang_packet_total, 2).'元的现金红包 ，请多多做好你朋友的服务工作。', 'color' => '#173177'],
                            ];
                        $wxgzh_service->sendTemplateMsg($gang_member_info['gzh_openid'], 'D9_B5cFMv05Pbr8mFa04_4_EIAvUuYY2ZnnihRQ_-h0', $data,'pages/index/welcome');
                    }
                }
                if ($user_info['openid']) {
                    // 发送小程序模板消息 (给买家)
                    $tData = ['keyword1' => ['value' => date('Y-m-d H:i:s', time())], 'keyword2' => ['value' => $product_name], 'keyword3' => ['value' => $order_info['total_money'].'元'], 'keyword4' => ['value' => $order_sn]];
                    $wx_service->sendTemplateMsg($openid, $order_info['prepay_id'], 'gg86uD9VeXnchz8ov4asgKTm3jlwpkpb21fLRuLIkH4', 'pages/order/orderdetails/orderdetails?id='.$order_sn, $tData);
                }
            }
            // }
        } else {
            $result = false;
        }
        // 返回状态给微信服务器
        if ($result) {
            $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } else {
            $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
    }
}
